import { md5 } from "./md5.js";
export let signfn = function (action, postParam) {
  let key = "da9b4b1e2d11f83d14cd98fbdc1975e3";
  let app_key = "545cd98f3dbda9b41e2d11ef83d14cdb";
  let act = action;
  // 时间戳
  let ts = (_) => new Date().getTime().toString();
  // 随机32位数
  let nonce = () => {
    let arr = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "A",
      "B",
      "C",
      "D",
      "E",
    ];
    let res = "";
    for (let i = 0; i < 32; i++) {
      let pos = Math.round(Math.random() * (arr.length - 1));
      res += arr[pos];
    }
    return res;
  };

  function getSign(params, app_key, key) {
    if (typeof params == "string") {
      return paramsStrSort(params);
    } else if (typeof params == "object") {
      let arr = [];
      for (let i in params) {
        arr.push(i + "=" + params[i]);
      }
      return paramsStrSort(arr.join("&"));
    }
  }

  function paramsStrSort(paramsStr) {
    let url = paramsStr;
    let arr = [];
    let p = url.split("&");
    for (let i in p) {
      let temp_arr = p[i].split("=");
      arr.push(temp_arr[0].toLowerCase() + "=" + temp_arr[1]);
    }
    let urlStr = arr.sort().join("&");
    let newUrl = urlStr + "&key=" + key;
    return md5(newUrl);
  }
  var params = {
    act,
    ts: ts(),
    nonce: nonce(),
    app_key,
  };

  // 转成字符串
  let signstr = JSON.stringify(params);
  let finalsign = signstr
    .replace(/{|}|"/g, "")
    .replace(/:/g, "=")
    .replace(/,/g, "&");
  let sign = getSign(params, app_key, key);
  if (postParam) {
    return {
      "auth-ts": params.ts,
      "auth-nonce": params.nonce,
      "auth-sign": sign,
      "auth-key": app_key,
    };
  } else {
    return {
      "auth-ts": params.ts,
      "auth-nonce": params.nonce,
      "auth-sign": sign,
      "auth-key": app_key,
    };
  }
};
